package org.example.weboj.service.impl;

import org.example.weboj.entity.User;
import org.example.weboj.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.*;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Optional;

@Service
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 使用 Optional 的 orElseThrow 方法处理找不到用户的情况
        User user = userMapper.findByUsername(username)
                .orElseThrow(() -> new UsernameNotFoundException("User not found with username: " + username));

        // 为角色添加ROLE_前缀，确保Spring Security权限验证正常工作
        String roleWithPrefix = "ROLE_" + user.getRole().toUpperCase();
        
        // 创建并返回 UserDetails 对象
        return new org.springframework.security.core.userdetails.User(
                user.getUsername(),
                user.getPasswordHash(), // 这里数据库已经存储的是加密后的密码
                Collections.singletonList(new SimpleGrantedAuthority(roleWithPrefix))
        );
    }
}